package websocket

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/xiaobaiskill/fang/internal/impl"
	"net/http"
	"time"
)
var(
	upgrader = websocket.Upgrader{
		// 允许跨域
		CheckOrigin:func(r *http.Request) bool{
			return true
		},
	}
)

func wsHandler(w http.ResponseWriter , r *http.Request){
	var(
		wsConn *websocket.Conn
		err error
		conn *impl.Connection
		stopbeat int
	)
	// 完成ws协议的握手操作
	// Upgrade:websocket
	if wsConn , err = upgrader.Upgrade(w,r,nil); err != nil{
		return
	}

	if conn , err = impl.InitConnection(wsConn); err != nil{
		goto ERR
	}

	addConn(conn)


	for{
		if err = conn.WriteMessage([]byte("heartbeat"));err != nil{
			stopbeat++
			if stopbeat > 3 {
				return
			}
			continue
		}
		stopbeat = 0
		time.Sleep(1*time.Second)
	}

ERR:
	conn.Close()

}

func Ws()gin.HandlerFunc{
	return func(c *gin.Context) {
		wsHandler(c.Writer,c.Request)
	}
}
